using System;
using System.Collections.Generic;
using System.Data.SqlTypes;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using ShopForWeb.Dtos.BasicView;
using ShopForWeb.Dtos.ViewModel;
using ShopForWeb.Models.Basic;
using ShopForWeb.Models.DbContexts;

namespace ShopForWeb.Services
{
  public class OrderServices
  {
    private ShopDbContext _Db;
    private IMapper _Mapper;
    public OrderServices(ShopDbContext db, IMapper mapper)
    {
      this._Db = db;
      this._Mapper = mapper;
    }
    public async Task<int> AddNewAsync(Order order, List<OrderDetails> detailslist)
    {
      order.OrderId = System.Guid.NewGuid().ToString();
      order.OrderState = "1";
      order.OrderTime = System.DateTime.Now.ToString("yyyy-MM-dd mm:hh:ss");
      order.TotalPrice = 0;
      foreach (var item in detailslist)
      {
        item.OrderId = order.OrderId;
        order.TotalPrice += item.SalePrice * item.Number;
      }
      _Db.OrderSet.Add(order);
      _Db.OrderDetails.AddRange(detailslist);

      return await _Db.SaveChangesAsync();
    }
    public async Task<int> DeleteAsync(string orderId)
    {
      var query1 = _Db.OrderSet.Where(o => o.OrderId == orderId);
      var query2 = _Db.OrderDetails.Where(o => o.OrderId == orderId);

      _Db.OrderSet.RemoveRange(query1);
      _Db.OrderDetails.RemoveRange(query2);

      return await _Db.SaveChangesAsync();
    }
    public async Task<PageView<OrderView>> GetPageAsync(string OrderState, int page, int size)
    {
      var query = _Db.OrderSet.Where(o => 1 == 1);
      if (OrderState != "") query = query.Where(o => o.OrderState == OrderState);

      query = query.OrderByDescending(o => o.OrderTime);
      var count = await query.CountAsync();
      var list = await query.Skip((page - 1) * size).Take(size).ToListAsync();
      return new PageView<OrderView>()
      {
        Total = count,
        Data = _Mapper.Map<List<OrderView>>(list)
      };
    }
    public async Task<PageView<DayAmountView>> GetDayAmount(int page, int size)
    {
      var query = _Db.OrderSet.Where(o => 1 == 1);
      var group = query.GroupBy(g => new
      {
        Day = g.OrderTime.Substring(0, 10)
      })
      .Select(g => new DayAmountView()
      {
        Day = g.Key.Day,
        Amount = g.Sum(o => o.TotalPrice),
        Count = g.Count()
      })
      .OrderByDescending(g => g.Day);

      var count = await group.CountAsync();
      var list = await group.Skip((page - 1) * size).Take(size).ToListAsync();

      return new PageView<DayAmountView>()
      {
        Total = count,
        Data = list
      };
    }

    public PageView<DayAmountView> GetDayAmountAsync(int page, int size)
    {
      throw new NotImplementedException();
    }
  }
}
